﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Cocon90.Lib.Web
{
    /// <summary>
    /// Excel下载辅助类
    /// </summary>
    public class excel
    {
        /// <summary>
        /// 将DataTable发送给Context下载
        /// </summary>
        /// <param name="table"></param>
        /// <param name="fileName"></param>
        public void downExcelFromTable(System.Data.DataTable table, string fileName)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<table>");
            sb.AppendLine("<tr>");
            for (int i = 0; i < table.Columns.Count; i++)
            {
                sb.Append("<th>" + table.Columns[i].Caption + "</th>");
            }
            sb.AppendLine("</tr>");
            for (int j = 0; j < table.Rows.Count; j++)
            {
                sb.AppendLine("<tr>");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    var cell = table.Rows[j][i];
                    double temp;
                    if (double.TryParse(cell + "", out temp))
                    {
                        sb.Append("<td>" + "'" + cell + "</td>");
                    }
                    else sb.Append("<td>" + cell + "</td>");

                }
                sb.AppendLine("</tr>");
            }

            sb.AppendLine("</table>");
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("" + fileName.TrimEnd(".xls".ToCharArray()) + ".xls"));
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            StreamWriter sw = new StreamWriter(HttpContext.Current.Response.OutputStream);
            sw.Write(sb.ToString());
            sw.Flush();
        }
    }
}
